package com.aly.beanValidate.core;

import com.aly.beanValidate.core.validator.CheckValidator;
import com.aly.beanValidate.core.validator.CheckValidators;
import com.aly.game.util.StringUtils;
import org.dom4j.Document;
import org.dom4j.Element;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class GlobalConfigs {
    private Map<String, CheckValidator> validators;
    private Map<String, Set<String>> fileAlias;

    private GlobalConfigs(Document document) throws Exception {
        validators = new HashMap<>();
        fileAlias = new HashMap<>();
        initValidators(document);
    }

    public static GlobalConfigs load(Document document) throws Exception {
        return new GlobalConfigs(document);
    }

    private void initValidators(Document document) throws Exception {
        for (Element element : document.getRootElement().elements()) {
            if (!"global".equals(element.getName())) {
                continue;
            }
            for (Element global : element.elements()) {
                switch (global.getName()) {
                    case "validators": {
                        buildValidators(global);
                        break;
                    }
                    case "fileAlias": {
                        buildAlias(global);
                        break;
                    }
                }
            }
        }
    }

    private void buildAlias(Element fileAlias) {
        for (Element alias : fileAlias.elements()) {
            if (!"alias".equals(alias.getName())) {
                continue;
            }
            String name = Util.attr(alias, "name");
            Set<String> file = new HashSet<>();
            for (Element element : alias.elements()) {
                if ("file".equals(element.getName())) {
                    String fileName = Util.attr(element, "name");
                    file.add(fileName);
                }
            }
            if (this.fileAlias.put(name, file) != null) {
                throw new RuntimeException(" 名字别称 重复");
            }
        }
    }

    private void buildValidators(Element validators) throws Exception {
        for (Element validator : validators.elements()) {
            CheckValidator validatable = CheckValidators.create(validator, this);
            String name = validatable.getName();
            if (StringUtils.isEmpty(name)) {
                throw new RuntimeException("全局校验器必须包含名字");
            }
            if (this.validators.put(name, validatable) != null) {
                throw new RuntimeException("全局校验器 名字重复");
            }
        }
    }

    public CheckValidator getValidators(String name) {
        return validators.get(name);
    }

    public Set<String> getAlias(String name) {
        return fileAlias.get(name);
    }
}
